# -*- coding:utf-8 -*-

from aip import AipOcr
import pytesseract
from PIL import Image
import os
import json
import traceback


class MyImageOCR(object):
    def __init__(self, ocr_type = None):  # 初始化
        self.__ocr_type = ocr_type

    def setOcrType(self, ocr_type):
        self.__ocr_type = ocr_type

    '''
    返回 识别结果数 和 结果文字列表
    '''
    def startOcr(self, file_path):
        if self.__ocr_type == 0:  # 百度OCR
            res_num, res_words_list = self.baiDuOCR(file_path)
            return res_num, res_words_list
        elif self.__ocr_type == 1:  # 本地识别
            res_num = 999  # 需优化，针对多图识别
            res_words_string = list()
            res_words_string.append(self.tesseractOcr(file_path))
            return res_num, res_words_string
        else:
            pass

    def readSettings(self, ocr_type):
        app_id = None
        app_key = None
        secret_key = None

        try:
            with open("settings.json", "r") as foo:
                temp_json = json.loads(foo.read())
            if ocr_type == 0:  # 百度OCR
                app_id = temp_json.get("baiDuOCR").get("APP_ID")
                app_key = temp_json.get("baiDuOCR").get("API_KEY")
                secret_key = temp_json.get("baiDuOCR").get("SECRET_KEY")
        except(Exception):
            # try需要保留
            print("in class myImageOcr readSetting")
            traceback.print_exc()

        return app_id, app_key, secret_key

    def getImageContent(self, image_path):
        try:
            with open(image_path, 'rb') as foo:
                return foo.read()
        except(Exception):
            traceback.print_exc()
            return None

    def baiDuOCR(self, file_path):  # 使用高精度文字识别
        try:
            # 读取配置文件，获得APP_ID、API_KEY、SECRET_KEY
            app_id, api_key, secret_key = self.readSettings(0)
            # 图像识别
            client = AipOcr(app_id, api_key, secret_key)
            image = self.getImageContent(file_path)
            if image is None:
                return None, None
            ocr_result = client.basicAccurate(image)
            ocr_res_num = ocr_result.get("words_result_num")  # OCR识别的结果数
            ocr_res_words = list()
            temp = ocr_result.get("words_result")
            print("temp = ")
            print(temp)
            for i in temp:
                ocr_res_words.append(i.get("words"))

            # test测试
            print("ocr_num=")
            print(ocr_res_num)
            print("ocr_words=")
            print(ocr_res_words)

            return ocr_res_num, ocr_res_words
        except(Exception):
            traceback.print_exc()
            return None, None

    def tencentOcr(self):
        pass
    
    def tesseractOcr(self, file_path):
        image = Image.open(file_path)
        tess_data_dir_config = '--tessdata-dir "E:\\Tesseract-OCR\\tessdata"'
        text = pytesseract.image_to_string(image, lang='chi_sim', config=tess_data_dir_config)
        text = text.replace(" ", "").replace("\n\n", "\n")
        print("text is a ", type(text))
        print(text)
        return text






